package com.hongminzheng.openapi.controller;

import com.github.pagehelper.PageInfo;
import com.hongminzheng.openapi.bean.Result;
import com.hongminzheng.openapi.bean.TableData;
import com.hongminzheng.openapi.pojo.Token;
import com.hongminzheng.openapi.service.TokenService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hmz
 * @version v1.0
 * @data 2020/09/29
 **/
@RestController
@RequestMapping("/token")
@Log4j
public class TokenController {
    /**
     * 创建服务层对象
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 增加
     * @param token
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result insertToken(Token token){
        try {
            tokenService.insert(token);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            return new Result(false, "添加失败");
        }
    }
    /**
     * 更新
     * @param token
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result updateToken(Token token){
        try {
            tokenService.updateByPrimaryKey(token);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            return new Result(false, "更新失败");
        }
    }

    /**
     * 分页查询所有
     * @param page
     * @param limit
     * @return tokenTableData
     */
    @GetMapping("/page")
    @ResponseBody
    public TableData<Token> findLayuiPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, String accessToken){
        Token token = new Token();
        token.setAccessToken(accessToken);

        TableData<Token> tokenTableData = new TableData<>();
        PageInfo<Token> tokenPageInfo = tokenService.findPage(page, limit,token);
        tokenTableData.setCount(tokenPageInfo.getTotal());
        tokenTableData.setData(tokenPageInfo.getList());
        return tokenTableData;
    }

    @PostMapping("/dels")
    @ResponseBody
    public Result dels(@RequestBody List<Token> tokenList) {
        //创建返回对象
        Result result = new Result();
        //创建循环，调用删除方法
        tokenList.forEach(token -> {
            tokenService.deleteByPrimaryKey(token.getId());
        });
        result.setStatus(true);
        result.setMessage("批量删除成功");
        return result;
    }

}
